package com.qf.shop.goods.service.impl;


import com.alibaba.fastjson.JSON;
import com.qf.shop.common.constants.RabbitMQCons;
import com.qf.shop.common.vo.GoodsPngVO;
import com.qf.shop.goods.entity.StockEntity;
import com.qf.shop.goods.service.GoodsPngService;
import com.qf.shop.goods.service.StockService;
import com.qf.shop.common.vo.GoodsVo;
import com.qf.shop.goods.utils.VoUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.shop.common.utils.PageUtils;
import com.qf.shop.common.utils.Query;

import com.qf.shop.goods.dao.GoodsDao;
import com.qf.shop.goods.entity.GoodsEntity;
import com.qf.shop.goods.service.GoodsService;
import org.springframework.transaction.annotation.Transactional;
/**
 * @author:could
 * @Date:2021/08/13/10:17
 */
@Service("goodsService")
@Slf4j
public class GoodsServiceImpl extends ServiceImpl<GoodsDao, GoodsEntity> implements GoodsService {

    @Autowired
    private GoodsPngService goodsPngService;

    @Autowired
    private StockService stockService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<GoodsEntity> page = this.page(
                new Query<GoodsEntity>().getPage(params),
                new QueryWrapper<GoodsEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    @Transactional
    public void addGoods(GoodsVo goodsVo) {

        // 1.把VO转成entity然后再保存
        GoodsEntity goodsEntity = new GoodsEntity();
        BeanUtils.copyProperties(goodsVo,goodsEntity); // 属性名称一样就会拷贝过去，把goods中的属性拷贝到goodsEntity中

        // 2.插入商品信息
        baseMapper.insert(goodsEntity); // MP会自动完成主键回填，回填对象的id

        // 3.插入商品图片
        List<GoodsPngVO> goodsPngList = goodsVo.getGoodsPngList();
        for (GoodsPngVO goodsPngVo : goodsPngList) {
            goodsPngVo.setGid(goodsEntity.getId()); // 给商品的图片设置商品的id
        }
        goodsPngService.saveBatch(VoUtils.GoodsPngVOToGoodsPngEntity(goodsPngList));

        // 4.插入商品的库存
        StockEntity stockEntity = new StockEntity();
        stockEntity.setGid(goodsEntity.getId());
        stockEntity.setStock(goodsVo.getStock());
        stockEntity.setWid(1);
        stockService.save(stockEntity);


        // 把商品发送给MQ，同步给ES
        goodsVo.setId(goodsEntity.getId());
        String goodsVoJson = JSON.toJSONString(goodsVo);
        log.debug("goodsVoJson:{}",goodsVoJson);
        rabbitTemplate.convertAndSend(RabbitMQCons.GOODS_EXCHANGE,"goods.save",goodsVoJson);

    }

}